/**
 * Created by Administrator on 2015/6/10.
 */
var util = require('util');
var http = require('http');
var url =  require("url");
var iconv = require('iconv-lite');
var fs=require('fs');
var BufferHelper = require('bufferhelper');
var queryString=require('querystring');
try { var unzip = require('zlib').unzip } catch(e) { /* unzip not supported */ }
var logging = require('../../lib/logging.js');
var log_level='DEBUG';
var logger = logging.getLogger('addressToLocation-service','abc',log_level);
var db=require("./DbOperator");
/**
 *
  * @param address
 */
var requestUrlTemp=function(address){
    var ak="uqo4NpVsqsAh5hBaMF4zGWwg";
    var baiduHead="http://api.map.baidu.com/geocoder/v2/";
    var param="?ak=%s&output=json&address=%s";
    var result=baiduHead+param;
    result= util.format(result,ak,encodeURIComponent(address));

    return result;
}
var requestHeader=function(){
    var header={
        "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like NeoCrawler) Chrome/31.0.1650.57 Safari/537.36",
        "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Accept-Encoding":"gzip",
        "Accept-Language":"zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4",
        "Content-Type": 'application/x-www-form-urlencoded'
    };
    return header;
}
var options=function(reqUrl){
    //logger.log(reqUrl);
    var urlObj=url.parse(reqUrl);
    var option={
        'host':urlObj['host'],
        'port':urlObj['port'],
        'method':'GET',
        'path':urlObj['path'],
        'header':requestHeader()
    };
    return option;
};
var get_page_encoding = function(header){
    var page_encoding = 'UTF-8';
    //get the encoding from header
    if(header['content-type']!=undefined){
        var contentType = header['content-type'];
        var patt = new RegExp("^.*?charset\=(.+)$","ig");
        var mts = patt.exec(contentType);
        if (mts != null)
        {
            page_encoding = mts[1];
        }
    }
    return page_encoding;
}
var doRequest=function(shopid,address){
    var request=http.request(options(requestUrlTemp(address)));
    request.on('response',function(response){
       var compressed = /gzip|deflate/.test(response.headers['content-encoding']);
       var page_encoding=get_page_encoding(response.headers);
       page_encoding = page_encoding.toLowerCase().replace('\-','')
       var bufferHelper=new BufferHelper();
       response.on('data',function(data){
           bufferHelper.concat(data);
       });
       response.on('end',function(err,socket){
          var result;
          if(!compressed || typeof unzip=='undefined'){
              result=iconv.decode(bufferHelper.toBuffer(),page_encoding);
              updateLocation(shopid,result);
          }else{
              unzip(bufferHelper.toBuffer(),function(err,buff){
                  if(!err && buff){
                      result=iconv.decode(buff,page_encoding);
                      updateLocation(shopid,result);
                  }else{
                      logger.error("unzip failure");
                  }
              });
          }
       }) ;
    });
    request.on('error',function(err,socket){
        console.log(err);
    });
    request.end();
};
/**
 *
 * {
status: 0,
result: {
location: {
lng: 113.31753116422,
lat: 23.032648948107
},
precise: 0,
confidence: 50,
level: ""
}
}
 * @param shopid
 * @param result
 */
var updateLocation=function(shopid,result){
    try{
        var rt= JSON.parse(result);
        var lng=rt['result']['location']['lng'];
        var lat=rt['result']['location']['lat'];
        var sql="UPDATE xbq_shop_info SET lng='%s',lat='%s',locationStatus='1' WHERE id='%s'";
        sql=util.format(sql,lng,lat,shopid);
        db.executeSqlCallback(sql,function(rows){
            console.log("executeSql success:"+sql);
        });
    }catch(e){
         updateLocationStatus(shopid,'2',result);
        logger.error(e);
    }
}
/**
 *
 */
var updateLocationStatus=function(shopid,stauts,reason){
    var sql="UPDATE xbq_shop_info SET locationStatus='%s',locationErrorReason='%s'  WHERE id='%s'";
    sql=util.format(sql,stauts,reason,shopid);
    db.executeSqlCallback(sql,function(rows){
    });
}
var doTransLocation=function(){
    //locationStatus地址是否已经转换过了（0为未转换,1为已经转换,2为已经转换但是失败的）
    var sql="SELECT	id,address FROM xbq_shop_info WHERE lng IS  NULL AND lat IS NULL and locationStatus='0' and address!='undefined' ORDER BY id DESC LIMIT 0,50";
    db.executeSqlCallback(sql,function(rows){
       for(i in rows){
           doRequest(rows[i]['id'],rows[i]['address']);
       }
    });
}

setInterval(function(){
    logger.log("doTransBegin-------");
    doTransLocation();
    logger.log("doTransAround++++++");
},30*1000);